package com.wr.security;

import com.wr.pojos.PermissionEntity;
import com.wr.pojos.RoleEntity;
import com.wr.pojos.UserEntity;
import com.wr.services.PermissionService;
import com.wr.services.RoleService;
import com.wr.services.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName: MyRealm
 * @Description: shiro授权与认证
 * @author 吴睿
 * @date 2016-11-29
 **/
@Component
public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionService permissionService;

    /**
     * 授权
     * @param principals    身份
     * @return  返回值
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = String.valueOf(principals.getPrimaryPrincipal());

        final UserEntity user = userService.selectByUsername(username);
        final List<RoleEntity> roleInfos = roleService.selectRolesByUserId(user.getId());
        for (RoleEntity role : roleInfos) {
            // 添加角色
            System.err.println(role);
            authorizationInfo.addRole(role.getRoleSign());

            final List<PermissionEntity> permissions = permissionService.selectPermissionsByRoleId(role.getId());
            for (PermissionEntity permission : permissions) {
                // 添加权限
                System.err.println(permission);
                authorizationInfo.addStringPermission(permission.getPermissionSign());
            }
        }
        return authorizationInfo;
    }

    /**
     * 登录验证
     * @param token token
     * @return  返回值
     * @throws AuthenticationException  认证异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String mobile = String.valueOf(token.getPrincipal());
        String password = new String((char[]) token.getCredentials());
        // 通过数据库进行验证
        final UserEntity authentication = userService.authentication(new UserEntity(mobile, password));
        if (authentication == null) {
            throw new AuthenticationException("用户名或密码错误.");
        }
        return new SimpleAuthenticationInfo(authentication, password, getName());
    }
}
